package org.jeecg.modules.app.shopmember.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.ApiLogin;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.app.shopmember.service.AppShopMemberService;
import org.jeecg.modules.app.util.check.CheckUtil;
import org.jeecg.modules.power.shop.entity.YlShop;
import org.jeecg.modules.power.shop.service.IYlShopService;
import org.jeecg.modules.power.user.entity.YlShopMemberType;
import org.jeecg.modules.power.user.entity.YlShopMemberUser;
import org.jeecg.modules.power.user.entity.YlUser;
import org.jeecg.modules.power.user.service.IYlShopMemberTypeService;
import org.jeecg.modules.power.user.service.IYlShopMemberUserService;
import org.jeecg.modules.power.user.service.IYlUserService;
import org.jeecg.modules.system.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @BelongsProject: jeecg-boot-parent
 * @BelongsPackage: org.jeecg.modules.app.shopmember.controller
 * @Author: mi
 * @CreateTime: 2024-08-10 14:49
 * @Description:
 */
@CrossOrigin
@Api(tags = "APP运营端-门店会员权益相关接口")
@RestController
@RequestMapping("/api/appShopMember")
public class AppShopMemberController {

    @Autowired
    private IYlShopMemberTypeService ylShopMemberTypeService;

    @Autowired
    private IYlShopService ylShopService;//店铺数据


    @Autowired
    private IYlUserService ylUserService;//用户表

    @Autowired
    private IYlShopMemberUserService ylShopMemberUserService;


    @Autowired
    private  AppShopMemberService appShopMemberService;



    //获取门店会员类行  getShopMemberTypeList
    @ApiLogin
    @ApiOperation("APP运营端-获取门店会员类行")
    @GetMapping("/getShopMemberTypeList")
    public Result<?> getShopMemberTypeList(HttpServletRequest request){
        return Result.OK(ylShopMemberTypeService.list());
    }

    //根据门店id 获取响应分类
    @ApiOperation(value = "APP运营端-根据门店id 获取门店会员分类", notes = "返回 name 名称, month 会员有效期 月份 ,每日免费小时")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "店铺id", required = true),
    })
    @GetMapping("/getShopMemberTypeData")
    public Result<YlShopMemberType> getShopMemberTypeData(String id){
        if (oConvertUtils.isEmpty(id))return Result.error_599("店铺id不可为空");
        YlShop shop= ylShopService.getById(id);
        if (oConvertUtils.isEmpty(shop))return Result.error_599("店铺数据错误");
        if (oConvertUtils.isEmpty(shop.getShopMemberId())){
            //默认 普通门店会员
            shop.setShopMemberId("1821821960204386306");
            ylShopService.updateById(shop);
        }
        YlShopMemberType shopMemberType= ylShopMemberTypeService.getById(shop.getShopMemberId());
        Result<YlShopMemberType> result = new Result<YlShopMemberType>();
        result.setCode(200);
        result.setResult(shopMemberType);
        return result;
    }
    //提交 权益会员
    @ApiLogin
    @ApiOperation(value = "APP运营端-门店权益会员提交", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tel", value = "手机号", required = true),
            @ApiImplicitParam(name = "shopId", value = "店铺id", required = true),
    })
    @PostMapping("/addShopMemberUserApp")
    public Result<?>addShopMemberUserApp(HttpServletRequest request,String tel,String shopId){
        SysUser user=new ObjectMapper().convertValue(request.getAttribute("sysUser"),SysUser.class);//转对象 用户登陆对象
        if (oConvertUtils.isEmpty(shopId))return Result.error_599("店铺id不可为空");
        if (!CheckUtil.isPhone(tel)){
            return Result.error_599("请填入有效的手机号");
        }
        //判断 用户是否存在
        List<YlUser> ifUser= ylUserService.list(new LambdaQueryWrapper<YlUser>().eq(YlUser::getTel,tel));
        if (ifUser.size()==0)return Result.error_599("添加失败！用户不存在");
        //判断店铺有几个在进行中的 权益会员  每个店铺最多2个权益会员
        YlShop shop= ylShopService.getById(shopId);
        if (oConvertUtils.isEmpty(shop))return Result.error_599("店铺数据错误");
        Integer haveUser= ylShopMemberUserService.count(new LambdaQueryWrapper<YlShopMemberUser>().eq(YlShopMemberUser::getShopId,shopId).eq(YlShopMemberUser::getStatus,1).eq(YlShopMemberUser::getDelFlag,1));
        if (haveUser>1){
            return Result.error_599("每个店铺最多只能有2个权益会员！");
        }
        Date date=new Date();
        YlShopMemberType shopMemberType= ylShopMemberTypeService.getById(shop.getShopMemberId());
        //执行添加
        YlShopMemberUser ylShopMemberUser =new YlShopMemberUser();

        ylShopMemberUser.setUserId(ifUser.get(0).getId());
        ylShopMemberUser.setTel(tel);
        ylShopMemberUser.setShopId(shopId);
        ylShopMemberUser.setShopName(shop.getShopName());
        ylShopMemberUser.setTel(tel);
        ylShopMemberUser.setShopMemberId(shop.getShopMemberId());
        ylShopMemberUser.setName(shopMemberType.getName());
        ylShopMemberUser.setMonth(shopMemberType.getMonth());
        ylShopMemberUser.setHour(shopMemberType.getHour());
        ylShopMemberUser.setStatus(1);//进行中
        ylShopMemberUser.setBeginTime(date);//开始时间
        ylShopMemberUser.setEndTime(DateUtils.addMonthToDate(date,shopMemberType.getMonth()));//会员结束日期
        ylShopMemberUser.setCreateUser(user.getId());//创建者id
        ylShopMemberUser.setCreateBy(user.getUsername());
        ylShopMemberUser.setDelFlag(1);
        ylShopMemberUserService.save(ylShopMemberUser);
        return Result.OK("添加成功");
    }

    //门店详情进入=权益会员

    @ApiLogin
    @ApiOperation(value = "APP运营端-门店详情进入权益会员", notes = "APP运营端-门店详情进入权益会员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "shopId", value = "店铺id", required = true),
    })
    @PostMapping("/getShopMemberUserAppList")
    public Result<List<YlShopMemberUser>>getShopMemberUserAppList(HttpServletRequest request,String shopId){
        if (oConvertUtils.isEmpty(shopId))return Result.error_599("店铺id不可为空");
         List<YlShopMemberUser> shopMemberUserList= ylShopMemberUserService.list(new LambdaQueryWrapper<YlShopMemberUser>().eq(YlShopMemberUser::getShopId,shopId).eq(YlShopMemberUser::getDelFlag,1).orderByAsc(YlShopMemberUser::getStatus));
        Result<List<YlShopMemberUser>> result = new Result<List<YlShopMemberUser>>();
        result.setCode(200);
        result.setResult(shopMemberUserList);
        return result;
    }



    //删除
    @ApiLogin
    @ApiOperation(value = "APP运营端-权益会员-删除", notes = "APP运营端-门店详情进入权益会员-删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "数据id", required = true),
    })
    @PostMapping("/delShopMemberUserApp")
    public Result<?>delShopMemberUserApp(HttpServletRequest request,String id){
        if (oConvertUtils.isEmpty(id))return Result.error_599("id不可为空");
        YlShopMemberUser ylShopMemberUser= ylShopMemberUserService.getById(id);
        if (oConvertUtils.isEmpty(ylShopMemberUser))return Result.error_599("数据错误");
        ylShopMemberUser.setDelFlag(2);//标记删除
        ylShopMemberUserService.updateById(ylShopMemberUser);
        return Result.OK("删除成功");
    }



    @ApiLogin
    @ApiOperation(value = "APP运营端-权益会员-续费", notes = "APP运营端-门店详情进入权益会员-续费")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "数据id", required = true),
    })
    @PostMapping("/renewShopMemberUserApp")
    public Result<?>renewShopMemberUserApp(HttpServletRequest request,String id){
        SysUser user=new ObjectMapper().convertValue(request.getAttribute("sysUser"),SysUser.class);//转对象 用户登陆对象
        YlShopMemberUser ylShopMemberUser= ylShopMemberUserService.getById(id);
        if (oConvertUtils.isEmpty(ylShopMemberUser))return Result.error_599("数据错误");
        //取出店铺  校验 每个店铺只能有2个进行中的权益会员
         String shopId= ylShopMemberUser.getShopId();
        Integer haveUser= ylShopMemberUserService.count(new LambdaQueryWrapper<YlShopMemberUser>().eq(YlShopMemberUser::getShopId,shopId).eq(YlShopMemberUser::getStatus,1)
                .eq(YlShopMemberUser::getDelFlag,1).ne(YlShopMemberUser::getId,id));
        if (haveUser>1)return Result.error_599("续费失败！每个店铺最多只能有2个权益会员");
        Date date=new Date();
         Integer s=  ylShopMemberUser.getStatus();//1-进行中,2-已结束
        //开始续费
        YlShopMemberType shopMemberType= ylShopMemberTypeService.getById(ylShopMemberUser.getShopMemberId());
        if (oConvertUtils.isNotEmpty(shopMemberType)){//取出最新数据
            ylShopMemberUser.setName(shopMemberType.getName());
            ylShopMemberUser.setMonth(shopMemberType.getMonth());
            ylShopMemberUser.setHour(shopMemberType.getHour());
            ylShopMemberUser.setStatus(1);//进行中
            if (s==1){
                ylShopMemberUser.setEndTime(DateUtils.addMonthToDate(ylShopMemberUser.getEndTime(),shopMemberType.getMonth()));//结束时间往后延续
            }else {//已结束的
                ylShopMemberUser.setBeginTime(date);//开始时间
                ylShopMemberUser.setEndTime(DateUtils.addMonthToDate(date,shopMemberType.getMonth()));//结束时间往后延续
            }
        }else {
            //原数据续费
            if (s==1){//进行中
                ylShopMemberUser.setEndTime(DateUtils.addMonthToDate(ylShopMemberUser.getEndTime(),ylShopMemberUser.getMonth()));//结束时间往后延续
            }else {//已结束的
                ylShopMemberUser.setBeginTime(date);//开始时间
                ylShopMemberUser.setEndTime(DateUtils.addMonthToDate(date,ylShopMemberUser.getMonth()));//结束时间往后延续
            }
            ylShopMemberUser.setStatus(1);//进行中
        }
        ylShopMemberUser.setUpdateBy(user.getUsername());
        ylShopMemberUser.setUpdateUser(user.getId());
        ylShopMemberUser.setUpdateTime(date);
        ylShopMemberUserService.updateById(ylShopMemberUser);
        return Result.OK("续费成功");
    }






   //工具页面进入 门店会员列表

    @ApiLogin
    @ApiOperation(value = "APP运营端-门店会员列表", notes = "APP运营端-工具页面进入-门店会员列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "数量", required = true),
            @ApiImplicitParam(name = "shopMemberId", value = "门店权益类型", required = true),
    })
    @PostMapping("/getToolShopMemberUser")
    public Result<?>getToolShopMemberUser(HttpServletRequest request,
                                          @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                          @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                          String shopMemberId){
        if (oConvertUtils.isEmpty(shopMemberId))return Result.error_599("门店权益类型不能为空");
        SysUser user=new ObjectMapper().convertValue(request.getAttribute("sysUser"),SysUser.class);//转对象 用户登陆对象
        String bdId=null;
        String groupId=null;
        if (user.getIsLeaders().equals("1")){//组长 是否是组长  1 是 2不是
            groupId=user.getGroupIds();
        }else {
            bdId=user.getId();
        }
        Page<YlShopMemberUser> page = new Page<YlShopMemberUser>(pageNo, pageSize);
        IPage<YlShopMemberUser> pageList = appShopMemberService.getToolShopMemberUserList(page, bdId, groupId,shopMemberId);
        return Result.OK(pageList.getRecords());
    }




   //门店会员列表 批量删除 或批量续费 editShopMemberUserApp

    @ApiLogin
    @ApiOperation(value = "门店会员列表 =批量删除或批量续费", notes = "APP运营端-门店会员列表 批量删除 或批量续费")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "数据id,多个已逗号隔开", required = true),

            @ApiImplicitParam(name = "type", value = "类型1续费2 删除 ", required = true),

    })
    @PostMapping("/editShopMemberUserApp")
    public Result<?>editShopMemberUserApp(HttpServletRequest request,String ids,Integer type){
        SysUser user=new ObjectMapper().convertValue(request.getAttribute("sysUser"),SysUser.class);//转对象 用户登陆对象
        if (oConvertUtils.isEmpty(type))return Result.error_599("数据类型不能为空");
        if (oConvertUtils.isEmpty(ids))return Result.error_599("请选择数据");
         List<String>mId=  Arrays.asList(ids.split(","));//要处理的
//        查数据
        List<YlShopMemberUser> shopMemberUserList= ylShopMemberUserService.listByIds(mId);
        if (shopMemberUserList.size()==0){
            return Result.error_599("数据错误");
        }
        Date date=new Date();
        if (type==1 || type==2){
            if (type==1 ){//续费
                for (YlShopMemberUser memberUser:shopMemberUserList) {
                    memberUser.setUpdateTime(date);
                    memberUser.setUpdateUser(user.getId());
                    memberUser.setUpdateBy(user.getUsername());
                    //开始续费
                    YlShopMemberType shopMemberType= ylShopMemberTypeService.getById(memberUser.getShopMemberId());
                    if (oConvertUtils.isNotEmpty(shopMemberType)){//取出最新数据
                        memberUser.setName(shopMemberType.getName());
                        memberUser.setMonth(shopMemberType.getMonth());
                        memberUser.setHour(shopMemberType.getHour());
                        memberUser.setStatus(1);//进行中
                        memberUser.setEndTime(DateUtils.addMonthToDate(memberUser.getEndTime(),shopMemberType.getMonth()));//结束时间往后延续
                    }else {
                        //原数据续费
                        memberUser.setEndTime(DateUtils.addMonthToDate(memberUser.getEndTime(),memberUser.getMonth()));//结束时间往后延续
                        memberUser.setStatus(1);//进行中
                    }
                }
                ylShopMemberUserService.updateBatchById(shopMemberUserList);
            }else {
                //删除
                for (YlShopMemberUser memberUser:shopMemberUserList) {
                    memberUser.setDelFlag(2);
                    memberUser.setUpdateTime(date);
                    memberUser.setUpdateUser(user.getId());
                    memberUser.setUpdateBy(user.getUsername());
                }
                //
                ylShopMemberUserService.updateBatchById(shopMemberUserList);
            }
            return Result.OK("操作成功");
        }

        return Result.error_599("类型错误");


    }

















}
